<template>
  <div class="city">
    <top-bar class="top-bar">
      <template #left>
        <div @click="backClick">
          <i class="iconfont icon-fanhui"></i>
        </div>
      </template>
      <template #center>
        <span>当前城市</span>
      </template>
    </top-bar>

    <van-index-bar class="index-bar" :index-list="indexList">
      <div v-for="item in cityList" :key="item.index">
        <van-index-anchor class="index-anchor" :index="item.index" />
        <van-cell
          :title="city.name"
          v-for="city in item.list"
          :key="city.cityId"
          @click.native="cityClick(city.cityId, city.name)"
        />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import axios from "axios";
import TopBar from "@/components/TopBar";
import Vue from "vue";
import { IndexBar, IndexAnchor, Cell } from "vant";
Vue.use(IndexBar);
Vue.use(IndexAnchor);
Vue.use(Cell);

export default {
  data() {
    return {
      cityList: [],
      indexList: [],
    };
  },
  components: { TopBar },
  methods: {
    backClick() {
      this.$router.back();
    },
    handleCity(cityData) {
      let letterArr = []; // 准备生成 ["A", "B", ...,"Y", "Z"]
      let newList = []; // 最终城市格式 [{index:"A",list:["城市"]}]
      // 生成A-Z ["A", "B", ...,"Y", "Z"]
      for (let i = 65; i < 91; i++) {
        letterArr.push(String.fromCharCode(i));
      }
      // for j循环26次，每次循环找对应的字母
      for (let j = 0; j < letterArr.length; j++) {
        // arr是遍历筛选出一致的数组，执行26次任务，从A-Z的顺序 筛选出后端字母和创建的A-Z一致的数据
        let arr = cityData.filter(
          (item) => item.pinyin.substr(0, 1) == letterArr[j].toLowerCase()
        );
        // 如果这个arr不是空数组，则按照格式push到新arr里面
        if (arr.length > 0) {
          newList.push({
            index: letterArr[j],
            list: arr,
          });
        }
      }
      // 返回生成的最终城市格式
      return newList;
    },
    handleCityIndex(cityList) {
      let indexList = [];
      cityList.forEach((value) => {
        indexList.push(value.index);
      });
      return indexList;
    },
    cityClick(cityId, cityName) {
      console.log(cityId, cityName);
      // 本地存储 localStorage.setItem("键", "值");
      localStorage.setItem("cityId", cityId);
      localStorage.setItem("cityName", cityName);
      // this.$router.push(this.$store.state.toCityPath);
      this.$router.back();
    },
  },
  mounted() {
    axios({
      url: "https://m.maizuo.com/gateway?k=275971",
      headers: {
        "X-Client-Info":
          '{"a":"3000","ch":"1002","v":"5.0.4","e":"1614444947506870565437441","bc":"110100"}',
        "X-Host": "mall.film-ticket.city.list",
      },
    }).then((res) => {
      // 把返回的结果传给handleCity方法，并调用
      this.cityList = this.handleCity(res.data.data.cities);
      this.indexList = this.handleCityIndex(this.cityList);
    });
  },
};
</script>

<style scoped  lang="less" >
.nav-bar {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 99;
}
.index-bar {
  margin-top: 44px;
}
</style>